
//本页面的session用于sip电话
var callSession;

var timeOutTask;

//本次通话唯一id
var callSessionId;

var thisUA;//此页面专用的SIPUA

//  先检测父页面UA有没有存在,不存在则初始化一次
function connectionUA() {
    if(parent.myUA!=null&&parent.myUA!=undefined){
        thisUA = parent.myUA;
        //如果UA不为空时，执行外呼操作
        listenUA();
        callNew();
    }else{
        //先进行注册操作
        checkFreeswitchUA();
    }
}


//加载浏览器
function checkCanCall(){
    console.log(navigator.appVersion.toLowerCase());
    var agent = navigator.appVersion.toLowerCase();
    var version = agent.match(/chrome\/([\d.]+)/)[1];
    version = version.substring(0,version.indexOf("."));
    console.log(version);
    if(agent.indexOf("chrome") > 0 && version >= 29) {
        console.log("当前浏览器版本可供外呼操作");
        if(commitTo == 8){
            var flag = checkUaRegisterStatus();//检测freeswitch连接状态
            if(flag == true){
                thisUA = parent.myUA;
                listenUA();
                //检测fs连接成功
                console.log("检测freeswitch连接成功 "+thisUA);
                showStatusForPage("检测freeswitch连接成功");
                //检测并发起外呼操作
                callNew();
            }else{
                //检测账号
                checkFreeswitchUA();
            }
        }
    }else{
        receiveCloseCall("检测当前浏览器版本无法执行外呼操作");
    }
}


/**
 * 检测账号
 */
function checkFreeswitchUA(){
    console.log("=============检测freeswitch账号信息==================");
    $.ajax({
        type:"POST",
        url:baseUrl + "/linkageCall/checkFreeswitchUA",
        async: false,
        cache:false,
        dataType:"json",
        success:function(data){
            if(data.code=="success"){
                console.log("freeswitch账号可用");
                //通过账号登录freeswitch
                uaName = data.msg;
                parent.initSIP(data.msg);
                console.log("Freeswitch初始化成功");
                checkUaRegisterStatusFun();//检测是否注册成功
            }else{
                var desc = data.msg;
                if(desc==null || desc==""){
                    desc = "检测账号异常，无法进行使用！";
                }
                receiveCloseCall(desc);
                return;
            }
        },
        error:function(data){
            parent.layer.alert('检测操作异常'+data.message(),{icon: 5,zIndex: parent.layer.zIndex });
            return;
        }
    });
}

/**
 * 检测UA的状态
 * */
function checkUaRegisterStatus() {
    console.log("检测freeswitch连接状态");
    var flag = false;
    try{
        if(parent.myUA != null && parent.status !="notConnected"){
            uaName = parent.freeswitchUser;
            thisUA = parent.myUA;
            flag = true;
            console.log("freeswitch uName ====>"+ uaName);
        }
    }catch (e){
        flag = false;
    }
    console.log("检测freeswitch连接状态，是否连接：" + flag);
    return flag;
}

/**
 * 检测Freeswtich用户是否注册成功
 * */
function checkUaRegisterStatusFun(){
    console.log("=============checkConnFsWsStatus(检测连接fs连接状态)================检测次数："+checkUaRegisterStatusCount);
    var flag = checkUaRegisterStatus();
    //清除定时任务的参数
    checkUaRegisterStatusCount--;
    checkUaRegisterStatusTask = null;
    clearTimeout(checkUaRegisterStatusTask);
    if(flag==true){
        //检测fs连接成功
        console.log("检测freeswitch连接成功");
        showStatusForPage("检测freeswitch连接成功");
        //开启监听UA事件
        listenUA();
        //检测并发起外呼操作
        callNew();
    }else {
        if (checkUaRegisterStatusCount > 0) {
            if (checkUaRegisterStatusTask == null) {
                console.log("再次发起检测连接操作");
                showStatusForPage("检测连接操作时间有点漫长，请耐心稍候……");
                checkUaRegisterStatusTask = setTimeout(function(){
                    checkUaRegisterStatusFun()
                }, 3000);
            }
        } else {
            //返回错误信息，并将通话标识为异常
            receiveCloseCall("检测连接freeswitch连接失败，无法发起外呼");
        }
    }
}




function listenUA() {
    // 接受入站（用户代理服务器）会话
    thisUA.on('invite', function (inComingSession) {

        callSession = inComingSession;
        //初始化呼入session;
        initComingSession(inComingSession);

        //freeswitch当前注册用户
        var displayName = inComingSession.remoteIdentity.displayName;

        console.log("当前freeswitch注册用户为" + displayName);

        inComingSession.accept({
            media: {
                constraints: {audio: true,video:false},

                render: {
                    remote: {audio: $("#remoteAudio").get(0)},
                    local:  {audio:$("#localAudio").get(0)}
                },

                RTCConstraints: {"optional": [{'DtlsSrtpKeyAgreement': 'true'}]}
            }
        });
    });
}
    

/**
 * 初始化freeswitch的session(呼入)
 * @param inComingSession
 */
function initComingSession(inComingSession) {

    inComingSession.on("accepted", function (data) {
        console.log("freeswitchLog: 收到请求成功的最终回复:"+data.substr(data.search(/[2][0-9][0-9]/),3));
        clearTimeout(timeOutTask);
        outgoingStop()
    });

    inComingSession.on("connecting", function () {
        console.log("freeswitchLog:  通话正在连接被叫");
        outgoingRing();
        timeOutTask = setTimeout('connectTimeOut(inComingSession)', 15000);
    });

    inComingSession.on("rejected", function (response, cause) {
        console.log("freeswitchLog:  通话已拒绝");
        outgoingStop();
    });

    inComingSession.on('bye', function (request) {
        console.log("freeswitchLog:  通话结束");
        outgoingStop();
        //stopTime();
    });

    inComingSession.on('cancel', function (request) {
        console.log("freeswitchLog:  通话被终止");
        $("#txResult").text("通话结束");//重置按钮
        resetBtn();
        outgoingStop();
        //stopTime();
    });


    inComingSession.on('failed', function (request) {
        console.log("freeswitchLog: 通话建立失败原因"+JSON.stringify(request));
        outgoingStop();
    });

}

/**
 * 铃声1播放
 */
function incomingRing() {
    //callPhonebody.find
    $("#ringtone").get(0).play();
}

/**
 * 铃声2播放
 */
function outgoingRing() {

    // callPhonebody.find("#outgoing").get(0).play();
    $("#outgoing").get(0).play();
}

/**
 * 铃声1停止
 */
function incomingStop() {
    //callPhonebody.find("#ringtone").get(0).pause();
    $("#ringtone").get(0).pause();
}

/**
 * 铃声2停止
 */
function outgoingStop() {
    //callPhonebody.find("#outgoing").get(0).pause();
    $("#outgoing").get(0).pause();
}


function connectTimeOut(inComingSession) {

    if (inComingSession == null || inComingSession == undefined) {
        console.log("freeswitchLog:  连接超过15秒,通话将自动关闭");
        outgoingStop();
    } else {
        console.log("freeswitchLog:  连接超过15秒,通话将自动关闭");
        inComingSession.bye();
        outgoingStop();
    }
}


/**
 * 最底层的浏览器关闭,切断通话
 */
$(window.top).on('unload',function(){

    if (callSession!=null&&callSession!=undefined){
        callSession.bye();
    }
});

if(callSession!=null&&callSession!=undefined){
    //挂断电话
    callSession.bye();
}